import sys
import os
import string

import simpleweb.admin.plugins.templates.python as pytemplate
import simpleweb.admin.plugins.templates.css as csstemplate
import simpleweb.admin.plugins.templates.html as htmltemplate
import simpleweb.admin.plugins.templates.js as jstemplate

import simpleweb.utils

def create_project(name, args, parser):
    """
Creates a new simpleweb project Project-Name. The new project
will have the neccessary files and filesystem structure that
a simpleweb project requires.


arguments: <project-name> [summary] [description-string]
    """

    option, args = parser.parse_args(args)

    if len(args) < 1 or len(args) > 3: 
        parser.print_usage()
        sys.exit()

    summary = ""
    description = ""	
    try:
        projectname = args[0]
        summary = args[1]
        description = args[2]
    except IndexError:
        pass

    create_folder_toplevel(projectname, summary, description)
    create_file(projectname, 'main.py', pytemplate.main, 0755)
    create_file(projectname, 'config.py', pytemplate.config)
    create_file(projectname, 'urls.py', pytemplate.urls)
    create_file(projectname, 'models.py', pytemplate.models)
    create_folder(projectname, 'static', subfolders=['css', 'img', 'js'])
    create_file(projectname, 'static/css/main.css', csstemplate.main)
    create_file(projectname, 'static/js/ajax.js', jstemplate.ajax)
    create_file(projectname, 'static/js/ajaxRails.js', jstemplate.ajaxRails)
    create_file(projectname, 'static/js/main.js', jstemplate.main)
    create_folder(projectname, 'templates')
    create_file(projectname, 'templates/index.html', htmltemplate.index)
    create_file(projectname, 'templates/master.html', htmltemplate.master)
    create_folder(projectname, 'tests')
    controllers_project = "%s/%s" % (projectname, 'controllers')
    create_folder_toplevel(controllers_project, "The controllers package for %s" % (projectname), "This package contains standalone controllers for the project %s" % (projectname))
    create_file(projectname, 'controllers/index.py', pytemplate.index)

def create_folder_toplevel(projectname, summary="", description=""):
    try:
        os.mkdir(projectname)
        f = open("%s/__init__.py" % (projectname), 'w')
        #TODO: apply line wrap to 'description' so it looks good in pydoc
        f.write('"""\n%s\n\n%s\n"""' % (summary, description))
        f.close()
    except Exception, e:
        simpleweb.utils.msg_warn("Error creating toplevel: %s" % (e))

def create_folder(projectname, foldername, subfolders=[]):
    try:
        fname = "%s/%s" % (projectname, foldername)
        os.mkdir(fname)
        for f in subfolders:
            create_folder(fname, f)
    except Exception, e:
        simpleweb.utils.msg_warn("Error creating folder: %s" % (e))

def create_file(projectname=None, filename='main.py', template=None, perms=0644, **kw):
    try:
        if projectname:
            fname = "%s/%s" % (projectname, filename)
        else:
            fname = filename

        f = open(fname, 'w')

        if template:
            content = string.Template(template)
            content = content.substitute(projectname=projectname, **kw)
        else:
            content = ""
        #TODO: pass in a dict() of 'templatekey=realvalue' pairs
        # so we're more flexible
        f.write(content)
        f.close()
        os.chmod(fname, perms)
    except Exception, e:
        simpleweb.utils.msg_warn("Error creating file: %s" %(e))
